package com.leecode.xiehf.page_01;

/**
 * https://leetcode-cn.com/problems/longest-common-prefix/
 * 编写一个函数来查找字符串数组中的最长公共前缀。
 * <p>
 * 如果不存在公共前缀，返回空字符串 ""。
 */
public class Solution_0014 {

    public static void main(String[] args) {
        Solution_0014 solution_0014 = new Solution_0014();
        String result = solution_0014.longestCommonPrefix(new String[]{"flower", "fl", "flight"});
        System.out.println(result);
    }

    public String longestCommonPrefix(String[] strs) {
        if (strs.length == 0) {
            return "";
        }
        if (strs.length == 1) {
            return strs[0];
        }
        String str = strs[0];
        int i = 0;
        for (; i < str.length(); i++) {
            for (int j = 1; j < strs.length; j++) {
                if (i > strs[j].length() - 1) {
                    return str.substring(0, i);
                }
                if (str.charAt(i) != strs[j].charAt(i)) {
                    return str.substring(0, i);
                }
            }
        }
        return str.substring(0, i);
    }
}
